package com.easydata.agent.config;

import com.alibaba.nacos.api.NacosFactory;
import com.alibaba.nacos.api.PropertyKeyConst;
import com.alibaba.nacos.api.config.ConfigService;
import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.api.naming.NamingFactory;
import com.alibaba.nacos.api.naming.NamingService;
import com.alibaba.nacos.api.naming.pojo.Instance;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;

import java.util.Properties;

@Configuration
public class NacosConfiguration {
    @Autowired
    Environment environment;

    @Bean
    NamingService namingServiceConfig() throws NacosException {
        Properties properties = new Properties();
        properties.setProperty(PropertyKeyConst.SERVER_ADDR, System.getenv("server"));
        properties.setProperty(PropertyKeyConst.NAMESPACE, "public");
        properties.put("username","nacos");
        properties.put("password","password");

        var naming = NamingFactory.createNamingService(properties);

        var ip = environment.getProperty("server.address");
        var port = Integer.parseInt( environment.getProperty("server.port"));
        naming.registerInstance("AGENT", ip, port );
        return naming;
    }

    @Bean
    ConfigService configServiceConfig() throws NacosException {
        Properties properties = new Properties();
        // example: localhost:8848
        properties.put("username","nacos");
        properties.put("password","password");
        properties.setProperty(PropertyKeyConst.SERVER_ADDR, System.getenv("server"));
        properties.setProperty(PropertyKeyConst.NAMESPACE, "public");
        var ret = NacosFactory.createConfigService(properties);
        return ret;
    }
}
